package com.dlyk.config.handler;

import com.dlyk.result.R;
import com.dlyk.util.JSONUtils;
import com.dlyk.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 登录失败处理器
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        // 登录失败的统一结果
        R result = R.FAIL(exception.getMessage());

        // 将R对象转成json
        String resultJson = JSONUtils.toJSON(result);

        // 将R对象以json形式返回给前端
        ResponseUtils.write(response, resultJson);
    }

}

